package cn.xingyun.pickaxe_loli_new.procedures;



import cn.xingyun.pickaxe_loli_new.Pickaxe_loli_new;
import cn.xingyun.pickaxe_loli_new.init.NewLoliPickaxeModItems;
import cn.xingyun.pickaxe_loli_new.item.LolipickaxeItem;
import cn.xingyun.pickaxe_loli_new.util.MyLevelEntityGetter;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.Holder;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.damagesource.DamageType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.item.PickaxeItem;
import net.minecraft.world.level.entity.*;
import net.minecraftforge.registries.ForgeRegistries;

import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.Level;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.Entity;
import net.minecraft.sounds.SoundSource;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.network.chat.Component;
import net.minecraft.core.BlockPos;

import java.util.List;
import java.util.Comparator;
import java.util.Objects;

import static net.minecraft.world.level.entity.EntityInLevelCallback.NULL;

public class RightOnLolipickaxeProcedure {
	public static void execute(LevelAccessor world, double x, double y, double z, Entity entity) {
		if (entity == null)
			return;
		double number = 0;
		{
			final Vec3 _center = new Vec3(x, y, z);
			List<Entity> _entfound = world.getEntitiesOfClass(Entity.class, new AABB(_center, _center).inflate(100 / 2d), e -> true).stream().sorted(Comparator.comparingDouble(_entcnd -> _entcnd.distanceToSqr(_center))).toList();
			for (Entity entityiterator : _entfound) {
				if (!(entityiterator instanceof Player _playerHasItem && _playerHasItem.getInventory().contains(new ItemStack(NewLoliPickaxeModItems.LOLIPICKAXE.get())))) {
					if (!entityiterator.level().isClientSide())
						if (entityiterator instanceof LivingEntity livingEntity) {
							LolipickaxeItem.addBanEntity(livingEntity);
							livingEntity.setHealth(0);
								livingEntity.die(new DamageSource(Holder.direct(new DamageType("",10)),entity));
								//livingEntity.dropLeash(true,true);
								livingEntity.hurtMarked = false;
								for (int i = 0;i<=100;i++){
									livingEntity.hurtTime=i+100;
									livingEntity.deathTime=i+100;
								}
								callBackRemove(entityiterator);
								ListRemoveEntity(entityiterator);

								/*try {
									Class c = mob.getClass();
									Method method = c.getDeclaredMethod("dropCustomDeathLoot", DamageSource.class);
									method.setAccessible(true);
									method.invoke(new DamageSource(Holder.direct(new DamageType("",10)),entity),1,true);
								}catch (Exception e) {
									System.out.println("无法获取掉落物");
								}*/

						}
						//entityiterator.discard();
					number = number + 1;
				}
			}
		}
		if (world instanceof Level _level) {
			if (!_level.isClientSide()) {
				_level.playSound(null, BlockPos.containing(x, y, z), Objects.requireNonNull(ForgeRegistries.SOUND_EVENTS.getValue(new ResourceLocation(Pickaxe_loli_new.MODID + ":lolisuccess"))), SoundSource.NEUTRAL, 1, 1);
			} else {
				_level.playLocalSound(x, y, z, Objects.requireNonNull(ForgeRegistries.SOUND_EVENTS.getValue(new ResourceLocation(Pickaxe_loli_new.MODID + ":lolisuccess"))), SoundSource.NEUTRAL, 1, 1, false);
			}
		}
		if (LolipickaxeItem.strongerRemove) {
			if (world instanceof ServerLevel _level) {
				_level.entityTickList.forEach((entity1 -> {
					if (entity1 instanceof Player player && player.getInventory().contains(NewLoliPickaxeModItems.LOLIPICKAXE.get().getDefaultInstance()))return;
					callBackRemove(entity1);
					ListRemoveEntity(entity1);
					banEntity(entity1);
					LolipickaxeItem.DarkNameList.add(entity1.getClass().getName());
				}));
			}
		}else if (entity instanceof Player _player && !_player.level().isClientSide())
			_player.displayClientMessage(Component.literal((("已攻击100格方块范围内的" + number) + "个实体")), false);
	}
	public static void callBackRemove(Entity entity) {
		if (entity.level() instanceof ServerLevel _level) {
			PersistentEntitySectionManager pesm = _level.entityManager;
					pesm.callbacks.onSectionChange(entity);
					pesm.callbacks.onTrackingEnd(entity);
					pesm.visibleEntityStorage.byId.remove(entity.id);
					pesm.visibleEntityStorage.byUuid.remove(entity.uuid);
					pesm.callbacks.onTickingEnd(entity);
					pesm.callbacks.onDestroyed(entity);
					pesm.knownUuids.remove(entity.getUUID());
					pesm.callbacks.onSectionChange(entity);
					entity.setLevelCallback(NULL);
			if (entity.levelCallback instanceof PersistentEntitySectionManager<?>.Callback callback) {
				pesm.sectionStorage.remove(callback.currentSectionKey);
				callback.realEntity=null;
			}
		}else if (entity.level() instanceof ClientLevel _level) {
			TransientEntitySectionManager pesm = _level.entityStorage;
			pesm.callbacks.onSectionChange(entity);
			pesm.entityStorage.byId.remove(entity);
			pesm.entityStorage.byUuid.remove(entity);
			pesm.callbacks.onTickingEnd(entity);
			pesm.callbacks.onTrackingEnd(entity);
			pesm.callbacks.onDestroyed(entity);
			pesm.callbacks.onSectionChange(entity);
			entity.setLevelCallback(NULL);
		}
	}
	public static void ListRemoveEntity(Entity entity){
		if (entity.level() instanceof ServerLevel _level) {
			_level.chunkSource.chunkMap.entityMap.remove(entity.id);
			_level.chunkSource.chunkMap.entitiesInLevel.clear();
			_level.entityTickList.remove(entity);
			_level.navigatingMobs.clear();
		}else if (entity.level() instanceof ClientLevel _level) {
			_level.tickingEntities.remove(entity);
			_level.partEntities.remove(entity);
		}
	}
	public static void banEntity(Entity entity){
		if (entity.level() instanceof ServerLevel _level) {
			_level.entityTickList.remove(entity);
			LolipickaxeItem.DarkNameList.add(entity.getClass().getName());
			LolipickaxeItem.SentityGetter = new MyLevelEntityGetter(_level.entityManager.visibleEntityStorage, _level.entityManager.sectionStorage);
		}else if (entity.level() instanceof ClientLevel _level) {
			_level.tickingEntities.remove(entity);
			_level.partEntities.remove(entity);
			_level.scoreboard.entityRemoved(entity);
			LolipickaxeItem.DarkNameList.add(entity.getClass().getName());
			LolipickaxeItem.CentityGetter = new MyLevelEntityGetter(_level.entityStorage.entityStorage, _level.entityStorage.sectionStorage);
		}
	}
}
